<template>
  <span v-if="label" :class="['dict-tag', `dict-tag-${tagClass}`]">
    {{ label }}
  </span>
  <span v-else>{{ value }}</span>
</template>

<script setup>
import { ref, watch, onMounted } from 'vue'
import { dictUtil } from '@/utils/dict'

const props = defineProps({
  value: {
    type: [String, Number],
    required: true
  },
  dictType: {
    type: String,
    required: true
  }
})

const label = ref('')
const tagClass = ref('')

// 加载字典标签
const loadLabel = async () => {
  try {
    const dictData = await dictUtil.getDictData(props.dictType)
    const item = dictData.find(d => d.dictValue === String(props.value))
    if (item) {
      label.value = item.dictLabel
      tagClass.value = item.listClass || 'default'
    } else {
      label.value = props.value
      tagClass.value = 'default'
    }
  } catch (error) {
    console.error('加载字典标签失败:', error)
    label.value = props.value
  }
}

// 监听值变化
watch(() => [props.value, props.dictType], loadLabel, { immediate: true })

onMounted(() => {
  loadLabel()
})
</script>

<style scoped>
.dict-tag {
  display: inline-block;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.dict-tag-default {
  background: #f3f4f6;
  color: #6b7280;
}

.dict-tag-primary {
  background: #e0e7ff;
  color: #4f46e5;
}

.dict-tag-success {
  background: #dcfce7;
  color: #16a34a;
}

.dict-tag-info {
  background: #e0f2fe;
  color: #0284c7;
}

.dict-tag-warning {
  background: #fef3c7;
  color: #d97706;
}

.dict-tag-danger {
  background: #fee2e2;
  color: #dc2626;
}
</style>